package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.domain.RequestParams;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.lucene.queries.function.FunctionScoreQuery;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public PageResult search(RequestParams requestParams) {
        try {
            // 当前页
            Integer page = requestParams.getPage();
            // 每页显示条数
            Integer size = requestParams.getSize();
            // 当前页的第一条数据
            Integer pageOpen = (page - 1) * size;

            // key = ""
            String key = requestParams.getKey();

            SearchRequest request = new SearchRequest("hotel");

            //if (key == null || "".equals(key)) {
            //    request.source().query(QueryBuilders.matchAllQuery());
            //} else {
            //    request.source().query(QueryBuilders.matchQuery("all", key));
            //}

            SearchSourceBuilder source = request.source();

            // 执行需要过滤的请求
            buildBasicQuery(requestParams, source);

            // 添加分页
            request.source().from(pageOpen).size(size);

            // 地理坐标查询
            String location = requestParams.getLocation();

            location = "31.21,121.5";
            if (StringUtils.isNotBlank(location)) {
                request.source().sort(
                        SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                                .order(SortOrder.ASC)
                                .unit(DistanceUnit.KILOMETERS)
                );
            }

            SearchResponse search = client.search(request, RequestOptions.DEFAULT);

            return handle(search);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 过滤获取索引库中的数据信息
    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("hotel");

            SearchSourceBuilder source = request.source();

            buildBasicQuery(requestParams, source);

            request.source().size(0);

            // 数据聚合
            extracted(request);


            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Aggregations aggregations = response.getAggregations();


            List<String> brandAgg = extracted(aggregations, "brandAgg");
            List<String> cityAgg = extracted(aggregations, "cityAgg");
            List<String> starAgg = extracted(aggregations, "starAgg");

            Map<String, List<String>> map = new HashMap<>();
            map.put("city", cityAgg);
            map.put("brand", brandAgg);
            map.put("starName", starAgg);

            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> extracted(Aggregations aggregations, String aggName) {
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();

        ArrayList<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        return list;
    }

    private void extracted(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
        request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(100));
        request.source().aggregation(AggregationBuilders.terms("starAgg").field("starName").size(100));
    }

    private void buildBasicQuery(RequestParams requestParams, SearchSourceBuilder source) {

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String key = requestParams.getKey();
        // 判断 key(关键字) 是否为空
        if (StringUtils.isBlank(key)) {
            // 查询所有
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            // 查询指定关键字
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }

        // 品牌查询
        String brand = requestParams.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }

        // 城市查询
        String city = requestParams.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }

        // 价格查询
        Integer maxPrice = requestParams.getMaxPrice();
        Integer minPrice = requestParams.getMinPrice();

        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price")
                    .lte(maxPrice)
                    .gte(minPrice)
            );
        }

        // 星级查询
        String starName = requestParams.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }

        // 相关性算分 (给广告酒店设置排序)
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );

        source.query(functionScoreQuery);
    }


    public PageResult handle(SearchResponse search) {
        SearchHits hits = search.getHits();
        // 获取查询的总条数
        long totalHits = hits.getTotalHits().value;
        // 获取查询的数据
        SearchHit[] searchHits = hits.getHits();


        List<HotelDoc> hotels = Arrays.stream(searchHits).map(arr -> {
            String sourceAsString = arr.getSourceAsString();

            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);

            // 获取最近的距离值
            Object[] sortValues = arr.getSortValues();

            if (sortValues != null || sortValues.length > 0) {
                // 设置距离的值
                hotelDoc.setDistance(sortValues[0]);
            }
            return hotelDoc;

        }).collect(Collectors.toList());

        return new PageResult(totalHits, hotels);
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            SearchRequest request = new SearchRequest("hotel");

            request.source().suggest(
                    new SuggestBuilder().addSuggestion("mySuggestion",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(prefix)
                                    .skipDuplicates(true)
                    )
            );

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Suggest suggest = response.getSuggest();
            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");

            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();

            ArrayList<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String result = option.getText().string();
                list.add(result);
            }
            return list;
        } catch (IOException e) {
            throw  new RuntimeException(e);
        }

    }


}
